﻿using Domain.IRepositorys;
using Domain.Services;
using Domain.Types;
using Infrastructure.Job;
using Infrastructure.UniOfWorkBase;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utility;
using static Utility.PolicyUtil;

namespace Application.Job
{
    [Job("0 0/10 * * * ? ")]
    public class TakeTaskOutTimeJob : AbstractJob
    {
        public TaskService taskService { get; set; }
        public ITaskTakeRepository taskTakeRepository { get; set; }
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public ILogger<TakeTaskOutTimeJob> Logger { get; set; }
        public override void Run()
        {
            var list = taskTakeRepository.Entities.Where(i => i.Status == TaskTakeAuditStatus.待提交 && i.AuditOutTime >= DateTime.Now).ToList();

            foreach (var item in list)
            {
                try
                {
                    var r = PolicyUtil.WaitAndRetry<bool>(new int[] { 1, 2, 2 }, () =>
                    {
                        return taskService.TakeTaskAuditPass(item.UserID, item.ID);
                    });
                }
                catch (PolicyRetryException ex)
                {
                    Logger.LogException(ex, item);
                }
            }
            
            
            list = taskTakeRepository.Entities.Where(i => i.Status == TaskTakeAuditStatus.待提交 && i.OutTime >= DateTime.Now).ToList();

            foreach (var item in list)
            {
                try
                {
                    PolicyUtil.WaitAndRetry(new int[] { 1, 2, 2 }, () =>
                    {
                            taskService.ReleaseTake(item);
                    });
                }
                catch (PolicyRetryException ex)
                {
                    Logger.LogException(ex,item);
                }

                //测试点 相同的Task 2个Take 第一个执行完成后 在另一个线程或数据库修改信息后是否能成功
            }


            
        }
    }
}
